/*
 * device.c
 *
 *  Created on: 2017
 *      Author: zjm
 */

#include "../mongoose.h"
#include "db.h"
#include "../json/json.h"
#include "../b64/base64.h"
/*
 *
 * [
 *    {"address":"21243354","name":"dsadsada"},
 *    {"address":"21243353","name":"dsadsada"},
 *    {"address":"21243355","name":"dsadsada"}
 * ]
 *
 * */
static char buffer[8192];
int get_device(struct mg_connection *nc,struct http_message *hm)
{
	dbFile db;
	char *rest = "undefined";
	struct json *J;
	int error;
	int count = 0;
	char base64[256];

	db_open("/data/data.db",&db);

	dbStart(&db);

	dbSql(&db,"select * from t_device;");

	J = json_open(JSON_F_NONE, &error);

	while(dbStep(&db) == SQLITE_ROW){
		int column = db_column_count(&db);
		json_push(J,"[#]",count);
		for (int i = 0; i < column; ++i) {
			const char *header = db_column_name(&db,i);
			const char *value = dbGetResultString(&db,i);
			if(!strcmp("name",header)){
				memset(base64,0,sizeof(base64));
				base64_encode(value,strlen(value),base64);
				json_setstring(J,base64,"$",header);
			}else{
				json_setstring(J,value,"$",header);
			}
		}
		json_pop(J);
		count ++;
	}

	json_printstring(J,buffer,sizeof(buffer),JSON_F_NONE,&error);

//	json_printfile(J,stdout,JSON_F_NONE);

	json_close(J);

	mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n");

	mg_printf_http_chunk(nc,buffer);

	mg_send_http_chunk(nc, "", 0);

	dbDone(&db);

	db_close(&db);

	return 0;
}

int set_device(struct mg_connection *nc,struct http_message *hm)
{
//	char var[512];
	struct json *J;
	int error;
	dbFile db;
	char sql[512];
	char name_utf8[128];

	db_open("/data/data.db",&db);

	dbStart(&db);

	dbSql(&db,"DELETE FROM [t_device];");

	dbStep(&db);

	if(mg_url_decode(hm->query_string.p,hm->query_string.len,buffer,sizeof(buffer),0) > 0){
		J = json_open(JSON_F_NONE, &error);

		error = json_loadbuffer(J,buffer,strlen(buffer));
		if(error == 0){
			int count = json_count(J,".[]");

//			printf("%d\n",count);
			for (int i = 0; i < count; ++i) {
				const char *address = json_string(J,"[#].address",i);
				const char *name = json_string(J,"[#].name",i);
				int circuit = json_number(J,"[#].circuit",i);

				memset(name_utf8,0,sizeof(name_utf8));
				base64_decode(name,strlen(name),name_utf8);

				dbStart(&db);

				snprintf(sql,sizeof(sql),"INSERT INTO [t_device] (address,name,circuit) VALUES ('%s',?,%d);",address,circuit);
				dbSql(&db,sql);

				sqlite3_bind_blob(db.stmt,1,name_utf8,strlen(name_utf8),NULL);

				error = dbStep(&db);
				if(error != SQLITE_DONE){
					printf("sql error:%s\n",sqlite3_errmsg(db.db));
				}

				dbDone(&db);
			}

		}
	}

	db_close(&db);

	mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n");

	mg_printf_http_chunk(nc,"{\"status\":\"ok\"}");

	mg_send_http_chunk(nc, "", 0);

	return 0;
}
